package com.epro.dx.receiver;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import com.epro.dx.BR;
import com.epro.dx.R;
import com.epro.dx.activity.AlarmActivity;
import com.epro.dx.activity.DetailActivity;
import com.epro.dx.activity.HomeActivity;
import com.epro.dx.activity.LPLocalBrowserActivity;
import com.epro.dx.activity.LoginActivity;
import com.epro.dx.activity.SpecialActivity;
import com.epro.dx.activity.StartUpActivity;
import com.epro.dx.activity.TrackSubscriptActivity;
import com.epro.dx.activity.order.ShippingTrackingActivity;
import com.epro.dx.listenner.CustomAsyncTaskListener;
import com.epro.dx.task.FeedBackNoticeTask;
import com.epro.dx.task.GetTrackConfigTask;
import com.epro.dx.task.SetNoticeReadTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.CustomToast;
import com.epro.dx.util.JGUtils;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.MessageServiceProvider;
import com.weipu.common.facade.model.MessageModel;
import com.weipu.common.facade.model.ModuleChildrenModel;
import com.weipu.common.facade.model.Parmars;
import com.weipu.common.facade.model.PushSettingsModel;
import com.weipu.common.facade.support.service.TaskExecutor;
import com.weipu.common.okhttp.JsonUtils;
import com.weipu.common.subject.MessageSubjectImpl;
import com.weipu.common.util.Logger;
import com.weipu.common.util.NotificationsUtils;
import com.weipu.common.util.StringUtil;
import com.weipu.common.util.utils.JsonFormat;

import cn.jpush.android.api.JPushInterface;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;

import static android.content.Context.NOTIFICATION_SERVICE;

/**
 * 指定ip推送 4404854  4398468  7427783
 */
public class JGReceiver extends BroadcastReceiver {
    private static final String TAG = "JPush";
    private int code;
    private String beenClickItem;
    private MessageModel messageModel;
    private boolean isNeedReSendJg;
    //    private static Intent mIntent;
    private static Intent mOldIntent;
    private PendingIntent pIntent;
    private int icon;

    @Override
    public void onReceive(Context context, Intent intent) {

        Bundle bundle = intent.getExtras();

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
            //send the Registration Id to your server...
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
            String message = bundle.getString(JPushInterface.EXTRA_EXTRA);
            Log.d(TAG, "参数》》: " + JsonFormat.format(message));
            if (!TextUtils.isEmpty(message)) {
                messageModel = JsonUtils.fromJson(message, MessageModel.class);
                JGUtils.getInstance().setMessageModel(messageModel);
                if (messageModel.getPushType() == 1) {
                    if (ActivityUtil.isLogin(context)) {
                        FeedBackNoticeTask feedBackNoticeTask = new FeedBackNoticeTask(messageModel.getNoticeID(), messageModel.getNoticeType());
                        TaskExecutor.doTaskInBackground(feedBackNoticeTask);
                    } else {
                        MessageSubjectImpl.getMessageSubjectImplInstance().notice(1, messageModel.getNoticeType());
                    }
                }
                refreshMessageNumber(context, 1);
                //通知观察者有新消息
                if (messageModel.getPushType() == 2) {
                    MessageSubjectImpl.getMessageSubjectImplInstance().notice(1, messageModel.getNoticeType());
                }
                if ("false".equals(StringUtil.getConfig(ServerConstant.MessageCenter.ISSHOWEVENTNOTICE, "true")) &&
                        MessageModel.NOTICETYPE_EVENT == messageModel.getNoticeType()) {
                    //不提示通知
                    return;
                }

                sendNotification(context, bundle, getIntentFromMessage(messageModel, context), messageModel);
            }
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 接收到推送下来的通知");
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);
            Log.d(TAG, "参数》》: " + JsonFormat.format(bundle.getString(JPushInterface.EXTRA_EXTRA)));


        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 用户点击打开了通知");
            Log.d(TAG, "ID>>>>" + JPushInterface.getRegistrationID(context));
            //执行页面跳转逻辑，启动一个服务请求服务器告知消息已被阅读
//            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//            List<RunningTaskInfo> runningTasks = am.getRunningTasks(1);
            //更新未读消息数量
            if (!ActivityUtil.isLogin(context)) {
                isNeedReSendJg = true;
                gotoLogin(context);
                return;
            }

            refreshUnReadCount(-1);
//            Intent i = intent.getParcelableExtra("Intent");
            //获取保存的Intent对象
            Intent i = JGUtils.getInstance().getmIntent();

            if (null != i) {
                //            	if(!"com.epro.dx".equals(runningTasks.get(0).topActivity.getPackageName().toString())){
//            		context.startActivity(i);
//            	}
                String noticeID = i.getStringExtra("NoticeID");
                if (!TextUtils.isEmpty(noticeID) && ActivityUtil.isLogin(context)) {
                    ArrayList<String> notices = new ArrayList<>();
                    notices.add(noticeID);
                    TaskExecutor.doTaskInBackground(new SetNoticeReadTask(MessageServiceProvider.ACTIONTYPE_NOTICEIDS, notices));
                }
                context.startActivity(i);
            }

        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            Log.w(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
        } else {
            Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
        }
    }


    /**
     * 发送自定义的锁屏通知
     *
     * @param context 上下文
     */
    private void sendCustomLockNoti(Context context) {
        //跳转到自己锁屏界面
        Intent alarmIntent = new Intent(context, AlarmActivity.class);
        alarmIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(alarmIntent);

    }

    /**
     * 发送系统状态栏通知，需要系统打开权限
     *
     * @param context 上下文
     */
    private void sendSysNoti(Context context, PendingIntent intent) {

        NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
//        pIntent = PendingIntent.getBroadcast(context, Integer.parseInt(subMsgID), toReceiverIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        pIntent = intent;

        //以下几行内容把通知往下拉才能看到
        android.support.v7.app.NotificationCompat.InboxStyle inboxStyle = new android.support.v7.app.NotificationCompat.InboxStyle(builder);
        inboxStyle.setBigContentTitle("DX");//消息的标题

        String[] contentSplit = messageModel.getTitle().split("\\r\\n");
        int length = contentSplit.length;

        if (contentSplit.length > 3) {
            inboxStyle.addLine(contentSplit[length - 3]);
            inboxStyle.addLine(contentSplit[length - 2]);
            inboxStyle.addLine(contentSplit[length - 1]);
        } else if (contentSplit.length == 3) {
            inboxStyle.addLine(contentSplit[length - 2]);
            inboxStyle.addLine(contentSplit[length - 1]);
        }

        builder.setAutoCancel(true)//设置点击通知时是否自动取消
                .setContentTitle(messageModel.getContent())//设置通知的标题
                .setContentText(length > 1 ? contentSplit[1] : "")//设置通知的内容
                .setContentIntent(pIntent)//设置点击通知的意图
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())//设置通知的事件
                .setStyle(inboxStyle)
                .setSmallIcon(icon);//设置通知的图标
        builder.setDefaults(Notification.DEFAULT_ALL);
        Notification notification = builder.build();
        manager.notify(code++, notification);


    }

    /**
     * 发送悬浮的通知
     *
     * @param context 上下文
     */
    private void sendFloatNoti(final Context context) {

        //使用普通的吐司,可以绕过系统的权限限制
        final CustomToast customToast = new CustomToast(context);
        customToast.setGravity(Gravity.TOP, 0, 0);
        customToast.setDuration(5000);
        ViewDataBinding binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.custom_notification, null, false);
        binding.setVariable(BR.info1, "DX");
        binding.setVariable(BR.info2, messageModel.getTitle());
        binding.getRoot().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customToast.hide();
                //先判断有没有登陆，如果没有登陆，先跳转到登陆界面
                if (!ActivityUtil.isLogin(context)) {
                    isNeedReSendJg = true;
                    gotoLogin(context);
                    return;
                }
                Intent toReceiverIntent = new Intent(JPushInterface.ACTION_NOTIFICATION_OPENED);
                context.sendBroadcast(toReceiverIntent);
            }
        });
        customToast.setView(binding.getRoot());
        customToast.show();

    }

    /**
     * 根据后台返回的数据获取分段获取内容
     *
     * @param title 后台返回的内容
     * @return 拆分拼接好的内容
     */
    private String getContent(String title) {
        String[] contentSplit = title.split("\\r\\n");
        int length = contentSplit.length;
        StringBuffer buffer = new StringBuffer();
        if (length == 4) {
            buffer.append(contentSplit[1])
                    .append("\r\n")
                    .append(contentSplit[2])
                    .append("\r\n")
                    .append(contentSplit[3]);
        } else if (contentSplit.length == 3) {
            buffer.append(contentSplit[1])
                    .append("\r\n")
                    .append(contentSplit[2]);
        }
        return buffer.toString();
    }


    /**
     * 跳转到登陆页面
     */
    private void gotoLogin(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra("Intent", mOldIntent);
        Bundle data = new Bundle();
        data.putInt(ServerConstant.Parameter.PARAMETER_NAME_LOGIN_ACTION_TYPE,
                ServerConstant.Parameter.PARAMETER_ACTION_TYPE_JGRECEIVER);
        //将订单号码传递至登陆界面
        if (messageModel != null) {
            data.putString(ServerConstant.Parameter.PARAMETER_NAME_ORDER_NUMBER, messageModel.getOrderNumber());
        }
        if (isNeedReSendJg) {
            data.putBoolean(ServerConstant.Parameter.PARAMETER_NAME_IS_NEED_RESEND_JG, isNeedReSendJg);
        }
        intent.putExtras(data);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        isNeedReSendJg = false;
    }

    /**
     * @param context
     * @创建：Tony 2016-5-5下午1:58:52
     * @描述：更新未读消息数量
     */
    private void refreshMessageNumber(Context context, int number) {
        StringUtil.saveConfig(ServerConstant.MessageCenter.UNREAD_MESSAGE, String.valueOf(true));
    }


    /**
     * @param messageModel
     * @创建：Tony 2016-4-18下午3:10:50
     * @描述：根据消息类型确定跳转页面
     */
    private Intent getIntentFromMessage(MessageModel messageModel, Context mContext) {
        if (null == messageModel) {
            return null;
        }
        Intent intent = new Intent();
        intent.putExtra("IsFromMessage", true);

        //增加是否需要校验活动是否过期的标记
        if (messageModel.getNoticeType() == MessageModel.NOTICETYPE_EVENT) {
            intent.putExtra("needCheckValid", true);
        }
        intent.putExtra("NoticeID", messageModel.getNoticeID());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        switch (messageModel.getLinkType()) {
            case MessageModel.LINKTYPE_PRODUCTLIST:
                //产品列表
                intent.putExtra(ModuleChildrenModel.ACTIVTYPE, Parmars.GETTYPE_MESSAGE);
                intent.putExtra(ModuleChildrenModel.ACTIVID, messageModel.getNoticeID());
                intent.putExtra("BannerName", messageModel.getTitle());
                intent.setClass(mContext, SpecialActivity.class);
                break;
            case MessageModel.LINKTYPE_PRODUCTDETAIL:
                //产品详情
                intent.setClass(mContext, DetailActivity.class);
                Bundle data = new Bundle();
                data.putInt(ServerConstant.Parameter.PARAMETER_NAME_PRODUCT_ID,
                        Integer.valueOf(messageModel.getSku()));
                intent.putExtras(data);
                break;
            case MessageModel.LINKTYPE_WAPURL:
                //网页
                intent.setClass(mContext, LPLocalBrowserActivity.class);
                intent.putExtra("URL", messageModel.getLinkUrl());
                intent.putExtra("PageTitle", messageModel.getTitle());
                intent.setClass(mContext, LPLocalBrowserActivity.class);
                break;
            case MessageModel.LINKTYPE_CONTENTTEXT:
                //主页
                ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
                List<RunningTaskInfo> runningTasks = am.getRunningTasks(1);

                //遗留问题 如果不判断，会数组越界
                if (runningTasks.size() == 0){
                    intent = null;
                }else {
                    if (!"com.epro.dx".equals(runningTasks.get(0).topActivity.getPackageName().toString())) {
                        intent.setClass(mContext, StartUpActivity.class);
                    } else {
                        intent = null;
                    }
                }

                break;

            case MessageModel.LINKTYPE_SHIPPINGDETAIL:
                //物流详情
                intent.setClass(mContext, ShippingTrackingActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("OrderNumber", messageModel.getOrderNumber())
                        .putExtra("CurrencyCode", "")
                        .putExtra("fromJG", true);
                break;
            default:

                break;
        }
        return intent;
    }

    @SuppressLint("SimpleDateFormat")
    private void sendNotification(Context context, Bundle bundle, Intent mIntent, MessageModel message) {
//        this.mOldIntent = mIntent;
        //将这次的意图保存起来
        JGUtils.getInstance().setIntent(mIntent);
        refreshUnReadCount(1);

        //为了确认用户是否点击，当用户点击通知时，在此开启本类，在用户点击的action中再次处理
        Intent toReceiverIntent = new Intent(JPushInterface.ACTION_NOTIFICATION_OPENED);
        if (null != toReceiverIntent) {
            toReceiverIntent.putExtra("Intent", mIntent);
        }
        //确认唯一ID
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat format = new SimpleDateFormat("ddHHmmss");
        int mid = Integer.parseInt(format.format(date));
        String msgID = bundle.getString(JPushInterface.EXTRA_MSG_ID);
        String subMsgID = msgID.substring(msgID.length() - 2);

        //根据系统版本选择图标样式

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            icon = R.drawable.icon_notice;
        } else {
            icon = R.drawable.icon;
        }

        sendNotice(context, message, toReceiverIntent, mid, subMsgID, icon);
    }

    /**
     * @param context          上下文
     * @param message
     * @param toReceiverIntent
     * @param mid
     * @param subMsgID
     * @param icon             epc.tmobile.com
     */
    private void sendNotice(Context context, MessageModel message, Intent toReceiverIntent, int mid, String subMsgID, int icon) {
        NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        pIntent = PendingIntent.getBroadcast(context, Integer.parseInt(subMsgID), toReceiverIntent, PendingIntent.FLAG_CANCEL_CURRENT);

        //send
        if (message.getLinkType() != MessageModel.LINKTYPE_SHIPPINGDETAIL) {
            //如果不是物流详情的通知

            builder.setContentTitle(message.getTitle())
                    .setContentText(message.getContent())
                    .setSmallIcon(icon)
                    .setWhen(System.currentTimeMillis())
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true)
                    .setContentIntent(pIntent);
            manager.notify(mid - Integer.parseInt(subMsgID), builder.build());

        } else {
            getPushConfig(context);
        }
    }

    private void getPushConfig(final Context context) {
        try {
            new GetTrackConfigTask(new CustomAsyncTaskListener<PushSettingsModel.DataBean>() {
                @Override
                public void onPostExecute(PushSettingsModel.DataBean pushSettingsModel) {
                    if (pushSettingsModel != null) {
                        boolean isPush = pushSettingsModel.isIsPush();
                        StringUtil.saveConfig("IsPush", isPush + "");
                        //如果通知类型为物流详情,且APP消息开关打开的时候
                        if (isPush) {
                            if (ActivityUtil.isLock(context)
                                    || Boolean.parseBoolean(StringUtil.getConfig(Constant.Global.IS_LOCK, true + ""))) {

                                sendCustomLockNoti(context);//如果是锁屏状态

                            } else if (ActivityUtil.isHome(context)) {

                                sendFloatNoti(context);//如果在桌面，则发送悬浮的通知

                            } else {

                                if (NotificationsUtils.isNotificationEnabled(context)) {
                                    sendSysNoti(context, pIntent);//不是在桌面，发送系统的通知
                                }
                            }
                        }
//                        //如果通知类型为物流详情,且APP消息开关打开的时候
//                        if (Boolean.parseBoolean(StringUtil.getConfig("IsPush", true + ""))) {
//                            if (ActivityUtil.isLock(context)
//                                    || Boolean.parseBoolean(StringUtil.getConfig(Constant.Global.IS_LOCK, true + ""))) {
//
//                                sendCustomLockNoti(context);//如果是锁屏状态
//
//                            } else if (ActivityUtil.isHome(context)) {
//
//                                sendFloatNoti(context);//如果在桌面，则发送悬浮的通知
//
//                            } else {
//
//                                if (NotificationsUtils.isNotificationEnabled(context)) {
//                                    sendSysNoti(context, pIntent);//不是在桌面，发送系统的通知
//                                }
//                            }
//                        }
                    }
                }

            }).execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 刷新未读消息的数量
     *
     * @param number 读取消息的数量
     */
    private void refreshUnReadCount(int number) {
        String unReadCountText = StringUtil.getConfig(ServerConstant.MessageCenter.UNREAD_MESSAGE_COUNT, "0");
        if (!TextUtils.isEmpty(unReadCountText) && TextUtils.isDigitsOnly(unReadCountText)) {
            int unReadCount = Integer.parseInt(unReadCountText);
            unReadCount += number;
            if (unReadCount <= 0) {
                StringUtil.saveConfig(ServerConstant.MessageCenter.UNREAD_MESSAGE, String.valueOf(false));
                unReadCount = 0;
            } else {
                StringUtil.saveConfig(ServerConstant.MessageCenter.UNREAD_MESSAGE, String.valueOf(true));
            }
            StringUtil.saveConfig(ServerConstant.MessageCenter.UNREAD_MESSAGE_COUNT, String.valueOf(unReadCount));
        }
    }
}
